import { INITIAL_FORM_STORE_VALUE, STORE_PRIORITY_LIST } from '@/views/store-settings/constants';
import { save, update, getStore, getThirdChannelInfo } from './api';
import { message } from '@/utils/util';
import { parseToObject } from '@/utils';

export default {
  name: 'store-settings-edit-modal',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    storeFormValueString: String,
    topChannelList: {
      type: Array,
      default: () => [],
    },
    cellularList: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      formValue: { id: null },
      formRules: {
        topChannelCode: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.topChannelCode) {
                callback('顶级渠道不能为空');
              } else {
                callback();
              }
            },
          },
        ],
        storeCode: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.storeCode) {
                callback('门店编码不能为空');
              } else {
                callback();
              }
            },
          },
        ],
        channelCode: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.channelCode) {
                callback('渠道编码不能为空');
              } else {
                callback();
              }
            },
          },
        ],
        channelName: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.channelName) {
                callback('渠道名称不能为空');
              } else {
                callback();
              }
            },
          },
        ],
        districtCode: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!this.formValue.districtCode) {
                callback('片区不能为空');
              } else {
                callback();
              }
            },
          },
        ],
        storeLevel: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.storeLevel) {
                callback('店型不能为空');
              } else {
                callback();
              }
            },
          },
        ],
        // storeType: [
        //   {
        //     required: true,
        //     trigger: 'change',
        //     validator: (rule, value, callback) => {
        //       if (!this.formValue.storeType) {
        //         callback('门店类型不能为空');
        //       } else {
        //         callback();
        //       }
        //     },
        //   },
        // ],
        cellularCode: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.cellularCode) {
                callback('所属蜂窝不能为空');
              } else {
                callback();
              }
            },
          },
        ],
        number: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.operationManagerNumber) {
                callback('城市运营经理不能为空');
              } else {
                callback();
              }
            },
          },
        ],
      },
      formLabelWidth: '110px',
      cellulars: [],
      onSubmitIng: false,
      storePriorityList: [],
    };
  },
  watch: {
    storeFormValueString(newValue) {
      if (!newValue) {
        return;
      }
      this.formValue = {
        ...this.formValue,
        ...parseToObject(newValue),
      };
      const { topChannelCode, storeType } = this.formValue;
      if (topChannelCode) {
        this.topChannelChange(topChannelCode);
        this.storeTypeChange(storeType, 'init');
      }
    },
  },
  methods: {
    async onSubmit(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          try {
            this.onSubmitIng = true;
            if (this.formValue.id) {
              await update(this.formValue);
            } else {
              await save(this.formValue);
            }
            this.onClose();
            this.resetTable();
            message('提示', '操作成功', 'success');
          } catch (e) {
            message('错误', e.message, 'error');
          }
          this.onSubmitIng = false;
        }
      });
    },
    resetTable() {
      this.$emit('resetTable');
    },
    onClose() {
      this.formValue = { ...INITIAL_FORM_STORE_VALUE };
      this.$refs.formRef.resetFields();
      this.cellulars = [];
      this.$emit('close');
    },
    cellularChange(value) {
      if (value) {
        this.cellularList.forEach(item => {
          if (value === item.cellularCode) {
            this.formValue.city = item.city;
          }
        });
      }
    },
    async storeCodeBlur() {
      const storeCode = this.formValue.storeCode;
      if (storeCode) {
        try {
          const store = await getStore(storeCode);
          const { areaCode = null, areaName = null, storeAddress = null } = store || {};
          if (!store) {
            this.formValue = {
              ...this.formValue,
              districtCode: null,
              districtName: null,
              address: null,
            };
            message('提示', '门店不存在', 'warning');
            return;
          }
          //获取三方平台店铺名称
          const channelCode = this.formValue.topChannelCode + '_' + this.formValue.storeCode;
          const channelInfo = await getThirdChannelInfo(channelCode);
          const { channelName = null, platformAccountCode = null } = channelInfo || {};
          if (!channelInfo) {
            message('提示', '门店映射不存在', 'warning');
            return;
          }
          this.formValue = {
            ...this.formValue,
            districtCode: areaCode,
            districtName: areaName,
            address: storeAddress,
            channelName: channelName,
            channelCode: channelCode,
            platformAccountCode: platformAccountCode,
          };
        } catch (e) {
          console.log(e);
          message('错误', '获取门店信息异常', 'error');
        }
      }
    },
    storeTypeChange(storeType, init) {
      if (storeType) {
        if (storeType === 'KEY_STORES') {
          this.storePriorityList = STORE_PRIORITY_LIST.keyStores;
        }
        if (storeType === 'NON_KEY_STORES') {
          this.storePriorityList = STORE_PRIORITY_LIST.nonKeyStores;
        }
      } else {
        this.storePriorityList = [];
      }
      if (!init) {
        this.formValue = {
          ...this.formValue,
          storePriority: '',
        };
      }
    },
    topChannelChange(code) {
      this.cellulars = [];
      if (code) {
        this.cellularList.forEach(item => {
          if (item.topChannelCode === code) {
            this.cellulars.push(item);
          }
        });
      }
      if (this.formValue.id) {
        this.formValue = { ...this.formValue, cellularCode: this.formValue.cellularCode };
      } else {
        this.formValue = {
          ...this.formValue,
          cellularCode: null,
          storeCode: null,
          districtCode: null,
          districtName: null,
          address: null,
          channelName: null,
          channelCode: null,
        };
        setTimeout(() => {
          this.$refs.formRef.clearValidate();
        }, 20);
      }
    },
  },
  mounted() {},
};
